import request from "@/utils/request";
import { reactive, computed, toRefs } from "vue";

// 使用表格操作 Hooks
// const { formData, loading, resetForm, handleSubmit }: any = useTableAdd(
//   "/system/sysRole/save",
//   initFormData,
//   formRef,
//   closeDialog,
//   () => emit("reset-table")
// );

/**
 * @description table 页面操作方法封装
 * @param {Function} api 获取表格数据 api 方法 (必传)
 * @param {Object} initParam 获取数据初始化参数 (非必传，默认为{})
 * @param {Function} dataCallBack 对后台返回的数据进行处理的方法 (非必传)
 * */
export const useTableAdd = (
  api = "",
  initParam: object = {},
  formRef?: any,
  closeDialog?: () => any,
  resetTable?: () => any,
  dataCallBack?: (data: any) => any,
  requestError?: (error: any) => void
) => {
  const state = reactive({
    // 初始化数据
    formData: JSON.parse(JSON.stringify(initParam)),
    //正在加载中
    loading: false,
  });

  /**
   * @description 重置表单
   * @return void
   * */
  const resetForm = () => {
    formRef.value.resetFields();
    formRef.value.clearValidate();

    state.formData = JSON.parse(JSON.stringify(initParam));
  };

  /**
   * @description 保存/更新
   * @return void
   * */
  const handleSubmit = async () => {
    formRef.value.validate(async (valid: any) => {
      if (valid && api) {
        try {
          const text = state.formData.id ? "编辑" : "新增";
          state.loading = true;
          const res: any = await request({
            url: api,
            method: "post",
            data: state.formData,
          });
          state.loading = false;

          // 有处理函数，则进行返回值数据处理
          let { data } = res;
          dataCallBack && (data = dataCallBack(data));
          ElMessage.success(`${text}成功`);
          closeDialog && closeDialog();
          resetTable && resetTable();
        } catch (error) {
          state.loading = false;
          requestError && requestError(error);
        }
      } else {
        return;
      }
    });
  };

  return {
    ...toRefs(state),
    handleSubmit,
    resetForm,
  };
};
